<template>
	<view class="challenges">
		<!-- <view class="navbar">
      <text class="title">我的挑战</text>
    </view> -->
		<!-- 数据统计 -->
		<!-- 数据统计 -->
		<view class="stats-container challenge-item">
			<view style="font-size: 10;" class="stat-item" v-for="item in stats" :key="item.type">
				<text style="font-size: 10;" class="stat-title">{{ item.title }}</text>
				<text style="font-size: 10;" class="animated-number">{{ item.displayValue }} {{ item.unit }}</text>
			</view>
		</view>

		<!-- <view class="challenge-list">
			<block v-for="(challenge, index) in challenges" :key="index">
				<view class="challenge-item">
					<text class="challenge-name">比赛名称：{{ challenge.name }}</text><br />
					<text class="challenge-date">时间：{{ challenge.date }}</text>
					<text class="challenge-status">地点：{{ challenge.status }}</text>
					<text class="challenge-rank">排名: {{ challenge.rank }}</text>
				</view>
			</block>
		</view> -->

		<view class="challenge-item">
			<!-- 遍历按年份和月份分组的挑战 -->
			<block v-for="year in Object.keys(groupedChallenges).sort((a, b) => b - a)" :key="year">
			    <view class="year-section">
			        <text class="year-title">{{ year }} 年</text>
			        <!-- 遍历月份 -->
			        <block v-for="month in Object.keys(groupedChallenges[year]).sort((a, b) => b - a)" :key="month">
			            <button v-if="groupedChallenges[year][month].length > 0" @click="toggleMonth(month)" class="month-button" style="margin-bottom: 10px;">
			                {{ month }} 月
			            </button>
			
			            <!-- 如果该月的比赛被选中，显示比赛列表 -->
			            <view v-if="selectedMonth === month">
			                <block v-for="(challenge, index) in groupedChallenges[year][month]" :key="index">
			                    <view class="challenge-item">
			                        <text class="challenge-name">比赛名称：{{ challenge.name }}</text><br />
			                        <text class="challenge-date">时间：{{ challenge.date }}</text>
			                        <text class="challenge-status">地点：{{ challenge.status }}</text>
			                        <text class="challenge-rank">排名: {{ challenge.rank }}</text>
			                    </view>
			                </block>
			            </view>
			        </block>
			    </view>
			</block>

		</view>

	</view>
</template>
<script>
	export default {
		data() {
			return {
				// 数据统计
				stats: [{
						type: 'distance',
						title: '总距离',
						unit: 'km',
						displayValue: 0
					},
					{
						type: 'calories',
						title: '燃烧卡路里',
						unit: 'kcal',
						displayValue: 0
					},
					{
						type: 'topSpeed',
						title: '最大速度',
						unit: 'km/h',
						displayValue: 0
					},
					{
						type: 'challenges',
						title: '参与挑战次数',
						unit: '',
						displayValue: 0
					},
					{
						type: 'duration',
						title: '总时长',
						unit: 'h',
						displayValue: 0
					},
					{
						type: 'pace',
						title: '平均配速',
						unit: 'km/h',
						displayValue: 0
					}
				],
				//挑战列表
				challenges: [],
				groupedChallenges: {},
				selectedMonth: null,
			};
		},
		async mounted() {
			this.fetchData();
			this.fetchChallenges();
		},

		methods: {

			useMockData() {
				// 假数据
				const mockData = [{
						type: 'distance',
						title: '总距离',
						unit: 'km',
						displayValue: 1200
					},
					{
						type: 'calories',
						title: '燃烧卡路里',
						unit: 'kcal',
						displayValue: 50000
					},
					{
						type: 'topSpeed',
						title: '最大速度',
						unit: 'km/h',
						displayValue: 500
					},
					{
						type: 'challenges',
						title: '参与挑战次数',
						unit: '',
						displayValue: 25
					},
					{
						type: 'duration',
						title: '总时长',
						unit: 'h',
						displayValue: 180
					},
					{
						type: 'pace',
						title: '平均配速',
						unit: 'km/h',
						displayValue: 4.5
					}
				];
				this.updateStats(mockData);
			},
			// 获取统计数据
			fetchData() {
				uni.request({
					url: 'https://your-backend-api-url.com/api/cycling/stats', // 替换为你的后台接口地址
					method: 'GET',
					success: (res) => {
						if (res.statusCode === 200 && res.data) {
							this.updateStats(res.data);
						} else {
							this.useMockData();
						}
						this.animateNumbers(); // 数据获取后启动动画
					},
					fail: (error) => {
						this.useMockData(); // 网络请求失败时使用假数据
						this.animateNumbers(); // 数据获取后启动动画
					},
				});
			},
			// 更新数据统计
			updateStats(data) {
				this.stats.forEach(stat => {

					// 从data数组中查找与当前stat类型匹配的对象
					const found = data.find(d => d.type === stat.type);
					// 如果找到匹配的对象
					if (found) {
						// 将found对象的value属性赋值给stat的displayValue属性
						stat.displayValue = found.displayValue;
					}
				});
			},
			// 实现数据动态显示的函数
			animateNumbers() {
				//console.log("123")
				const duration = 1000; // 动画持续时间（毫秒）
				const steps = 100; // 动画步数
				const interval = duration / steps; // 每步的时间间隔（毫秒）
				this.stats.forEach(stat => {
					let currentStep = 0;
					const targetValue = stat.displayValue; // 目标值

					// 初始化显示值为0
					stat.displayValue = 0;

					const updateNumber = setInterval(() => {
						currentStep++;
						// 逐步增加显示值
						stat.displayValue = Math.ceil((targetValue / steps) * currentStep);

						// 当达到目标值时停止动画
						if (currentStep >= steps) {
							stat.displayValue = targetValue;
							clearInterval(updateNumber);
						}
					}, interval);
				});
			},
			// 获取初始数据
			async fetchChallenges() {
				try {
					const response = await axios.get('/api/challenges');
					this.challenges = response.data;
					this.groupChallengesByMonth(); // 数据获取成功后按月份分组
				} catch (error) {
					uni.showToast({
						title: '加载挑战数据失败',
						icon: 'none'
					});
					this.setDefaultChallenges(); // 调用设置默认数据的方法
				}
			},
			// 获取数据失败出现默认数据
			setDefaultChallenges() {
				this.challenges = [{
						id: 1,
						name: '默认挑战1',
						date: '2024-08-01',
						status: '秋名山',
						rank: 20
					},
					{
						id: 2,
						name: '默认挑战2',
						date: '2024-08-02',
						status: '秋名山',
						rank: 30
					},
					{
						id: 3,
						name: '默认挑战3',
						date: '2024-07-03',
						status: '秋名山',
						rank: 40
					},
					{
						id: 4,
						name: '默认挑战4',
						date: '2023-07-03',
						status: '秋名山2',
						rank: 40
					}
				];

				this.groupChallengesByMonth(); // 设置默认数据后按月份分组
			},
			groupChallengesByMonth() {
				// 第一步：按月份分组
				const grouped = this.challenges.reduce((acc, challenge) => {
					const date = new Date(challenge.date);
					const year = date.getFullYear();
					const month = date.getMonth() + 1;
					// 创建年份的分组
					if (!acc[year]) {
						acc[year] = {};
					}

					// 创建月份的分组
					if (!acc[year][month]) {
						acc[year][month] = [];
					}
					// 将挑战添加到对应的年份和月份组
					acc[year][month].push(challenge);

					return acc;
				}, {});

				this.groupedChallenges = grouped;

			},

			// 切换显示的月份
			toggleMonth(month) {
				this.selectedMonth = this.selectedMonth === month ? null : month;
			},
		}
	}
</script>
<style scoped>
/* 通用容器样式 */
.stats-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 20px;
    background-color: #f7f8fa;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 数据项样式 */
.stat-item {
    width: 48%;
    margin: 10px 0;
    text-align: center;
    font-family: Arial, sans-serif;
    display: inline-block;
    box-sizing: border-box;
    padding: 10px;
    background-color: #ffffff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

/* 标题样式 */
.stat-title {
    font-size: 14px;
    color: #333;
    margin-bottom: 8px;
    font-weight: bold;
}

/* 动画数字样式 */
.animated-number {
    font-size: 20px;
    font-weight: bold;
    color: #4CAF50;
    animation: fadeIn 1.5s ease-in-out;
}

/* 淡入效果 */
@keyframes fadeIn {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}

/* 按年份分组的容器样式 */
.challenge-item {
    background-color: #ffffff;
    padding: 15px;
    margin-bottom: 15px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

/* 按钮样式 */
.month-button {
    background-color: #cdd7db;
    color: #ffffff;
    padding: 10px 15px;
    border: none;
    border-radius: 5px;
    font-size: 14px;
    cursor: pointer;
    transition: background-color 0.3s ease;
    width: 100%;
    text-align: left;
    margin-bottom: 10px;
}

.month-button:hover {
    background-color: #a8cbdb;
}

/* 挑战名称 */
.challenge-name {
    font-size: 16px;
    font-weight: bold;
    color: #2c3e50;
}

/* 日期、状态、排名 */
.challenge-date,
.challenge-status,
.challenge-rank {
    font-size: 14px;
    color: #7f8c8d;
    margin-top: 4px;
}

.year-section {
    margin-top: 20px;
}

.year-title {
    font-size: 18px;
    font-weight: bold;
    color: #34495e;
    margin-bottom: 10px;
    display: block;
}
</style>
